package com.ciwong.epaper.modules.onlineanswer;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.ciwong.epaper.modules.me.bean.WorkContents;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.common.CheckIsExamForDetail;
import com.ciwong.epaper.modules.epaper.bean.Result_scoce;
import com.ciwong.epaper.modules.epaper.dao.EpaperRequest;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.AddPointTypes;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.modules.share.QQShareHelper;
import com.ciwong.epaper.modules.share.QQShareListener;
import com.ciwong.epaper.modules.share.WxShareHelper;
import com.ciwong.epaper.modules.share.WxShareListener;
import com.ciwong.epaper.modules.share.bean.ShareMsgObj;
import com.ciwong.epaper.util.Base64Utils;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.ScoreUtils;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.widget.SubmitSuccessfulResultPage;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.widget.BuyServiceDialog;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.UiError;

/**
 * Created by albus on 2017/6/12.
 */

public class OnlineAnswerResultActivity extends BaseActivity implements View.OnClickListener {
    private Context mContext = this;
    SubmitSuccessfulResultPage srp_online_answer;
    protected int doWorkType;
    protected String tag = "";
    private Result_scoce mResult_scoce = new Result_scoce();
    private WorkContents mWorkContents;
    //截止时间
    private long effectiveDate;

    private int showScoreMode;
    private EApplication application;
    /**
     * 默认服务包剩余使用时间
     */
    private boolean serviceExpired;

    @Override
    protected int setView() {
        return R.layout.activity_online_answer_result;
    }

    ImageView iv_share_weichat_friendCircle;
    ImageView iv_share_weichat;
    ImageView iv_share_qq;
    ImageView iv_share_qq_space;

    @Override
    protected void findViews() {

        srp_online_answer = findViewById(R.id.srp_online_answer);
        iv_share_weichat_friendCircle = (ImageView) srp_online_answer.findViewById(R.id.share_weixin_friend);
        iv_share_weichat = (ImageView) srp_online_answer.findViewById(R.id.share_weixin);
        iv_share_qq = (ImageView) srp_online_answer.findViewById(R.id.share_qq);
        iv_share_qq_space = (ImageView) srp_online_answer.findViewById(R.id.share_qq_space);
        hideTitleBar();
    }

    @Override
    protected void initEvent() {
        srp_online_answer.setOnToRankListener(this);
        srp_online_answer.setOnCheckDetailListener(this);
        srp_online_answer.setOnCheckTipsListener(this);
        iv_share_weichat_friendCircle.setOnClickListener(this);
        iv_share_weichat.setOnClickListener(this);
        iv_share_qq.setOnClickListener(this);
        iv_share_qq_space.setOnClickListener(this);

    }

    /**
     * 1:作业，2：书桌
     */
    private int onlineAnswerFrom;
    /**
     * 作业耗时
     */
    private int workLong;
    /**
     * 作业总分
     */
    public float workScore;
    /**
     * 是否有主观题
     */
    private boolean isSubjective;
    //    private String title;
    private String contentId;
    String doWorkId;
    private long returnWorkLong;
    /**
     * 得分
     */
    private float actual_score;
    DownLoadInfo downLoadInfo;
    private long nowTime;

    @Override
    protected void preCreate() {
        super.preCreate();
        Intent intent = getIntent();
        onlineAnswerFrom = intent.getIntExtra(IntentFlag.INTENT_FLAG_TYPE, -1);
        workLong = intent.getIntExtra(IntentFlag.INTENT_FLAG_WORK_TIME, 0);
        returnWorkLong = intent.getLongExtra(IntentFlag.INTENT_FLAG_RETURN_WORK_LONG, 0);
        workScore = intent.getFloatExtra(IntentFlag.INTENT_FLAG_WORK_SCORE, 0f);
        actual_score = intent.getFloatExtra(IntentFlag.INTENT_FLAG_ACTUAL_SCORE, 0f);
        isSubjective = intent.getBooleanExtra(IntentFlag.INTENT_FLAG_SUBJECTIVE, false);
        contentId = intent.getStringExtra(IntentFlag.INTENT_FLAG_ID);
        effectiveDate = intent.getLongExtra(IntentFlag.INTENT_FLAG_WORK_EFFECTIV_TIME, 0);
        mWorkContents = (WorkContents) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_WORK_CONTENTS);
//        doWorkId = intent.getStringExtra(IntentFlag.INTENT_FLAG_DO_WORK_ID);
        doWorkId = intent.getStringExtra(IntentFlag.INTENT_FLAG_DO_WORK_ID);
        doWorkType = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_DO_WORK_TYPE, 0);
        downLoadInfo = (DownLoadInfo) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);

    }

    @Override
    protected void init() {
        application = (EApplication) getApplication();
        if (application != null) {
            //是否有购买vip
            serviceExpired = application.isServiceExpired();
        }
        if (!serviceExpired) {
            if (mWorkContents != null && mWorkContents.getIsFree() == 1) {
                serviceExpired = true;
            }
        }
        srp_online_answer.setDispayType(SubmitSuccessfulResultPage.DISPLAY_TYPE_ONLINE_ANSWER);
        //如果返回作业用时失败 则使用旧用时
        if (returnWorkLong != 0) {
            srp_online_answer.setWorkTime(ListenSpeakUtil.formatWorkLong(this, (int) returnWorkLong));
        } else {
            srp_online_answer.setWorkTime(ListenSpeakUtil.formatWorkLong(this, workLong));
        }
        srp_online_answer.setScoreText(ScoreUtils.subZeroAndDot(workScore + ""));//设置总分
        srp_online_answer.setToalScore(workScore);
        if (null != mWorkContents && mWorkContents.getWorkScore() > 0) {
            nowTime = mWorkContents.getNowDate();
            showScoreMode = mWorkContents.getShowScoreMode();
        }
        // 查看类型：0 提交立马能查看，1截止时间到后查看
        if (isSubjective) {//有主观题
            srp_online_answer.setEvaluateState(1, true, actual_score + "", ListenSpeakUtil.LsMode.SUBJECTIVE_MODE, nowTime, effectiveDate, showScoreMode, serviceExpired);

        } else {
            srp_online_answer.setEvaluateState(1, true, actual_score + "", ListenSpeakUtil.LsMode.HOME_WORK_MODE, nowTime, effectiveDate, showScoreMode, serviceExpired);
        }
        if (onlineAnswerFrom == OnlineAnswerCordovaActivity.FROM_HOME_WORK) {//来自作业
            srp_online_answer.setRankLinIsVis(View.VISIBLE);
        } else if (onlineAnswerFrom == OnlineAnswerCordovaActivity.FROM_DESK) {//来自书桌
            srp_online_answer.setRankLinIsVis(View.GONE);
        }
        isSupportQQAndQQZone();
        setValideSource(false);

        srp_online_answer.setOnRefreshScoreListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (NetworkUtils.isOnline()) {
                    refreshScoce();
                }

            }
        });
    }


    @Override
    protected void loadData() {
        if (doWorkType == 1) {
            tag = "订正错题  ";
        }
        srp_online_answer.setTitleText(tag + downLoadInfo.getResourceName());
        refreshScoce();
    }


    public void refreshScoce() {
        EpaperRequest.getOnlineScore(doWorkId, new BaseExtCallBack(OnlineAnswerResultActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void success(Object data) {
                mResult_scoce = (Result_scoce) data;
                if (mResult_scoce != null) {
                    try {
                        actual_score = Float.parseFloat(mResult_scoce.getActualScore());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    srp_online_answer.setEvaluateLastState(mResult_scoce, showScoreMode, nowTime, effectiveDate, serviceExpired);
                }
            }

            @Override
            public void failed(Object data) {
                CWLog.d("refresh", "refresh_scoce_fail");
                FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_ONLINE_ANSWER, data == null ? "" : "失败信息：" + getUrl() + " " + data.toString(), getMessage());

            }

            @Override
            public void failed(int errorCode, Object data) {
                CWLog.d("refresh", "refresh_scoce_fail" + errorCode);
                FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_ONLINE_ANSWER, data == null ? "" : "失败信息：" + getUrl() + " " + data.toString(), getMessage());

            }
        });
    }

    private String getMessage() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("获取评分失败: ")
                .append("doWorkId:").append(doWorkId).append("资源名称:").append(downLoadInfo.getResourceName());
        return stringBuilder.toString();
    }

    public void isSupportQQAndQQZone() {
        if (TextUtils.isEmpty(EConstants.QQ_APP_ID)) {
            iv_share_qq.setImageResource(R.mipmap.share_qq_unstalled);
            iv_share_qq_space.setImageResource(R.mipmap.share_qq_space_unstalled);
            iv_share_qq.setEnabled(false);
            iv_share_qq_space.setEnabled(false);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.rank_linear) {//排行榜
            MeJumpManager.jumpToRankH5Activity(R.string.go_back, this, contentId, downLoadInfo.getResourceName());
        } else if (id == R.id.ll_check_detail) {
            boolean orNotWatchDetails = CheckIsExamForDetail.INSTANCE.isOrNotWatchDetails(OnlineAnswerResultActivity.this, contentId + "", 0);
            if (!orNotWatchDetails)
                return;
            if (serviceExpired) {
                // 直接跳转到新的学习记录页面
                jumpToCheckDetail();
            } else {
                setBuyServiceDialog();
            }
        } else if (id == R.id.tx_score_result_encourage) {
            boolean orNotWatchDetails = CheckIsExamForDetail.INSTANCE.isOrNotWatchDetails(OnlineAnswerResultActivity.this, contentId + "", 0);
            if (!orNotWatchDetails)
                return;
            if (serviceExpired) {
                // 直接跳转到新的学习记录页面
                jumpToCheckDetail();
            } else {
                setBuyServiceDialog();
            }
        } else if (id == R.id.share_weixin_friend) {
            shareWeiChat(2);
        } else if (id == R.id.share_weixin) {
            shareWeiChat(1);
        } else if (id == R.id.share_qq) {
            qqShare("QQ");
        } else if (id == R.id.share_qq_space) {
            qqShare("QZone");
        }
    }

    private BuyServiceDialog buyServiceDialog;

    public void setBuyServiceDialog() {
        if (buyServiceDialog == null) {
            buyServiceDialog = new BuyServiceDialog(OnlineAnswerResultActivity.this);
            buyServiceDialog.setMenuOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    //拓展服务
                    MeJumpManager.jumpToResourseCenterH5Activity(OnlineAnswerResultActivity.this, R.string.go_back, getResources().getString(R.string.resource_center));
                    buyServiceDialog.dismiss();
                }
            });
            buyServiceDialog.setClosOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    buyServiceDialog.dismiss();
                }
            });
        }
        buyServiceDialog.show();
    }

    /**
     * "QQ"代表分享给QQ好友，"QZone"代表分享到QQ空间
     *
     * @param qq
     */

    private void qqShare(String qq) {
        try {
            ShareMsgObj shareMsgObj = new ShareMsgObj();
            shareMsgObj.setShareType(ShareMsgObj.ShareType.SHARE_WEB);
            shareMsgObj.setLocalImgUrl(FileUtil.getShareOnlineAnswerIconLocalPath(getApplicationContext()));
            shareMsgObj.setUrl(Base64Utils.getShareBase64Url(this, EpaperConstant.URL_ONLINE_PAPER_DETAIL_H5, downLoadInfo.getVersionId(), "0", doWorkId));
            String score = getString(R.string.speech_word_score, MeUtil.formatScore(actual_score));
            String shareContent = getString(R.string.str_share_content, score);
            if (isSubjective || (mResult_scoce != null && mResult_scoce.getStatus() == 17)) {
                shareContent = "快来看看我做的怎么样吧!";
            }
            if (qq.equals("QQ")) {
                shareMsgObj.setMsgDesription(shareContent);
                shareMsgObj.setMsgTitle(downLoadInfo.getResourceName());
                QQShareHelper.getInstance().shareToQQ(this, shareMsgObj, new QQShareListener() {
                    @Override
                    public void onQQShareSucc(Object var) {
                        shareAddPointType(doWorkId, AddPointTypes.SHERE_SCORE);
                    }

                    @Override
                    public void onQQShareFailure(UiError var1) {
                    }

                    @Override
                    public boolean onQQShareCancel() {
                        return false;
                    }
                });
            } else if (qq.equals("QZone")) {
                shareMsgObj.setMsgTitle(shareContent);
                shareMsgObj.setImg_url(FileUtil.getShareIconLocalPath(getApplicationContext()));
                QQShareHelper.getInstance().shareToQZone(this, shareMsgObj, new QQShareListener() {

                    @Override
                    public void onQQShareSucc(Object var) {
                        shareAddPointType(doWorkId, AddPointTypes.SHERE_SCORE);
                    }

                    @Override
                    public void onQQShareFailure(UiError var1) {

                    }

                    @Override
                    public boolean onQQShareCancel() {
                        return false;
                    }
                });
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    /**
     * @param wxType 1.微信会话,2微信朋友圈
     */
    private void shareWeiChat(int wxType) {
        WxShareHelper.getInstance().initWxShare(OnlineAnswerResultActivity.this, new WxShareListener() {
            @Override
            public void onWxShareing(String str) {

            }

            @Override
            public void onWxShareSucc(String var) {
                shareAddPointType(doWorkId, AddPointTypes.SHERE_SCORE);
            }

            @Override
            public void onWxShareFailure(int var, String var1) {

            }

            @Override
            public boolean onWxShareCancel() {

                return false;
            }
        });
        ShareMsgObj shareMsgObj = new ShareMsgObj();
        shareMsgObj.setWxType(wxType);

        shareMsgObj.setShareType(ShareMsgObj.ShareType.SHARE_WEB);

        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.onlineanswer_share_icon);
        shareMsgObj.setThunbBmp(bmp);

        shareMsgObj.setUrl(Base64Utils.getShareBase64Url(this, EpaperConstant.URL_ONLINE_PAPER_DETAIL_H5, downLoadInfo.getVersionId(), "0", doWorkId));
        String score = getString(R.string.speech_word_score, MeUtil.formatScore(actual_score));

        String shareContent = getString(R.string.str_share_content, score);
        if (isSubjective || (mResult_scoce != null && mResult_scoce.getStatus() == 17)) {
            shareContent = "快来看看我做的怎么样吧!";
        }
        if (wxType == 1) {
            shareMsgObj.setMsgTitle(downLoadInfo.getResourceName());
            shareMsgObj.setMsgDesription(shareContent);
        } else if (wxType == 2) {
            shareMsgObj.setMsgTitle(shareContent);
            shareMsgObj.setMsgDesription(downLoadInfo.getResourceName());
        }
        WxShareHelper.getInstance().sendReq(shareMsgObj);

    }

    private void shareAddPointType(String doWorkId, String type) {
        MeDao.getInstance().addPoint(EApplication.getInstance().getUserInfoBase().getUserId() + "", EApplication.getInstance().getUserInfoBase().getRealName(), type, doWorkId);
    }

    private void jumpToCheckDetail() {
        //http://prevm.teacher.jiaofuyun.com/v1706_moliban/onlinePaper/detail.html#clientId=20001&userId=543885408&brandId=524726977&versionId=634828917904331620&doWorkId=7217678200179671
        String clientId = EConstants.CLIENT_ID;
        String userId = EApplication.getInstance().getUserInfoBase().getUserId() + "";
        String brandId = EApplication.BRAND_ID + "";
        String versionId = downLoadInfo.getVersionId();
        String title;
        try {
            title = java.net.URLEncoder.encode(downLoadInfo.getResourceName(), "UTF-8");
        } catch (Exception e) {
            title = "";
        }
        title = title.replace("+", "%20");
        String url = EpaperConstant.URL_ONLINE_PAPER_DETAIL_H5 + "clientId=" + clientId + "&userId=" + userId + "&brandId=" + brandId + "&versionId=" + versionId
                + "&doWorkId=" + doWorkId + "&pageType=1" + "&packageId=" + downLoadInfo.getBookId() + "&cId=" + downLoadInfo.getChapterId() + "&doWorkType=" + doWorkType + "&title=" + title;
        MeJumpManager.jumpToStudyRecordH5Activity(-1, this, R.string.go_back, -1, url, downLoadInfo.getResourceName(), doWorkType);
    }

    @Override
    protected void onResume() {
        WxShareHelper.getInstance().onResumeResultData();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void finish() {
        if (onlineAnswerFrom == OnlineAnswerCordovaActivity.FROM_HOME_WORK) {
            Intent intent = new Intent(EpaperConstant.INTENT_BOACK_REF_WORK);
//        作业状态(1:已提交 2:退回 4:已批改完成 8:无法识别答题卡 16:等待批改)
            int workStatus = 1;//听说模考评分中传16，其他默认传1.
            if (isSubjective) {//在线作答有主观题
                workStatus = 17;
            }
            intent.putExtra(IntentFlag.INTENT_FLAG_WORK_STATUS, workStatus);//
            intent.putExtra(IntentFlag.INTENT_FLAG_ACTUAL_SCORE, actual_score);
            sendBroadcast(intent);
        }
        super.finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_QQ_SHARE || requestCode == Constants.REQUEST_QZONE_SHARE) {
            QQShareHelper.getInstance().onActivityResultData(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
